package com.springcloud.framework.servicea.controller;

import com.springcloud.framework.servicea.dao.UserRepository;
import com.springcloud.framework.servicea.entity.UserEntity;
import com.springcloud.framework.servicea.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

/**
 * @author zhanggm
 * @date 2021/4/26 10:01
 */
@RestController
@RequestMapping("/jpa/")
public class TestController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private EntityManager entityManager;

    @GetMapping("getPageInfo")
    public Object getPageInfo(UserEntity userEntity,
                              @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNun,
                              @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize) {
//        return userService.getPageInfo(userEntity, pageNun, pageSize);
//        return userRepository.selectListByNameLike2(userEntity.getName(),userEntity.getSex());


        StringBuffer sql = new StringBuffer("select * from t_user where 1=1");
        //拼接sql条件
        if (userEntity.getName() != null) {
            sql.append(" and name like '%" + userEntity.getName() + "%'");
        }
        //分页
        Query nativeQuery1 = entityManager.createNativeQuery(sql.toString().replace("*","count(1)"));
        BigInteger total = (BigInteger)nativeQuery1.getSingleResult();
        //计算分页
        Integer totalPage = (total.intValue()+pageSize-1)/pageSize;
        Integer startRow = (pageNun-1)*pageSize;
        Query nativeQuery = entityManager.createNativeQuery(sql.toString());
        nativeQuery.setFirstResult(startRow);
        nativeQuery.setMaxResults(pageSize);
        List resultList = nativeQuery.getResultList();
        return resultList;
    }
}
